<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Cache.php';
class Translate{
	protected static $_instance;
	private function __construct(){}
	private function __clone(){}
	public static function inst(){
	  if( null===self::$_instance ){
	    self::$_instance=new self();
		}
		return self::$_instance;
	}
	
	protected $errors=array('err'=>array(),'wrn'=>array());
	protected function error($msg){ $this->errors['err'][]=$msg; return false;}
	protected function warning($msg){ $this->errors['wrn'][]=$msg; return false;}
	public function getError(){ return $this->errors['err'][ count($this->errors['err'])-1 ]; }
	public function getErrors(){ return $this->errors['err']; }
	public function getWarning(){ return $this->errors['wrn'][ count($this->errors['wrn'])-1 ]; }
	public function getWarnings(){ return $this->errors['wrn']; }


	public function translate($str, $from, $to, $translit=false){
	  $query='translate_a/t?client=x&text='.urlencode($str).'&hl='.$from.'&sl='.$from.'&tl='.$to;
	  if($tst=Cache::inst()->get($query) )	return $tst->sentences[0]->trans;
//echo 'http://translate.google.com/'.$query;
	  try{
	    $json=file_get_contents('http://translate.google.com/'.$query);
		}catch(Exception $e){
		  return $this->error($e->getMessage());
		}
		$res= json_decode(iconv('windows-1251','utf-8',$json ));
//echo $json;echo '<pre>',print_r( $res, true),'</pre>';

	  if( !Cache::inst()->set( $query, $res, Cache::forever ) ){
	    $this->warning('ошибка кеширования - не удалось сохранить данные','wrn');
		}
		
	  if($translit)
		  return $res->sentences[0]->src_translit;
		else
	  	return $res->sentences[0]->trans;
	}
}
?>
